$(function () {

    $("#a4").click(function () {
        $("tbody").empty();
        let a1 = $("#a1").val();
        let a2 = $("#a2").val();
        let a3 = $("#a3").val();
        if (!a3) {
            $("<tr>" +
                "<td colspan='6'>没有航班信息</td></tr>").appendTo("tbody")
        } else {
            $.get("fly/findId", {"city_name": a2}, function (m1) {
                $.get("fly/findId", {"city_name": a3}, function (m2) {
                    $.get("fly/find", {
                        "flight_date": a1,
                        "take_airport_id": m1.id,
                        "landing_airport_id": m2.id
                    }, function (mess) {
                        if (mess.length > 0) {
                            for (var i = 0; i < mess.length; i++) {
                                $("<tr>" +
                                    "<td>" + mess[i].airline + "/" + mess[i].type + "</td>" +
                                    "<td>" + mess[i].take_time + "-" + mess[i].landing_time + "</td>" +
                                    "<td>" + m1.airport_name + "<br/>" + m2.airport_name + "</td>" +
                                    "<td>" + mess[i].flight_time + "</td>" +
                                    "<td>" + mess[i].stop_airport + "</td>" +
                                    "<td>" + mess[i].reference_price + "<br/><input type='button' value='查询机票' class='add-row' name='" + mess[i].id + "'>" + "</td>" +
                                    "</tr>").appendTo("tbody")
                            }
                        } else {
                            $("<tr>" +
                                "<td colspan='6'>没有航班信息</td></tr>").appendTo("tbody")
                        }

                    })
                })
            })

        }
    })

    // 为按钮绑定点击事件
    $(document).on('click', '.add-row', function () {
        var a1 = $(this).attr("name");
        var currentRow = $(this).closest('tr');
        // 获取当前按钮所在行
        // 检查当前行下面是否已经插入了机票信息行
        if (currentRow.next().hasClass("aaa")) {
            // 如果已经插入了，返回，不再插入
            return;
        }
        $.get("fly/tick", {"flight_id": a1}, function (momo) {
            // 创建新的行
            var length = momo.length;
            for (var i = length - 1; i >= 0; i--) {
                var newRows = "<tr class='aaa'>" +
                    "                    <td colspan='2'>" + momo[i].sell_company + "</td>" +
                    " <td colspan='2'>￥" + momo[i].ticket_price + "</td>" +
                    "          </tr>";
                currentRow.after(newRows);
            }

        })


    });


})